package com.test.springcloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
//import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * Created by qiutian on 16-10-21.
 */
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class EureApplication {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancer;

    /**
     * 从所有服务中选择一个服务（轮询）
     */
    @RequestMapping("/discover/{name}/{method}")
    public Object discover(@PathVariable String name,@PathVariable String method) {

        RestTemplate restTemplate = new RestTemplate();
        String url = "";
        for (int i = 0; i < 100000; i++) {
        	url = loadBalancer.choose(name).getUri().toString();
        	System.out.println(i + "," + url);
		}
        // String str = restTemplate.getForObject(url+"/"+method,String.class);
        return url;
    }

    /**
     * 获取所有服务
     */
    @RequestMapping("/services")
    public Object services() {
        // return discoveryClient.getInstances("server01");
    	return discoveryClient.getInstances("server02");
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(EureApplication.class).web(true).run(args);
    }
}
